package com.cms.bs.util;

import com.cms.bs.app.model.User;
import com.cms.bs.config.Constants;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;

import java.io.*;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by jiang on 2016-09-21.
 */
public class CommonUtil {

    public static String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"};

    /**
     * 格式化 日期
     *
     * @param format
     * @param date
     * @return
     */
    public static String formatDate(String format, Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 解析 日期
     *
     * @param format
     * @param date
     * @return
     */
    public static Date parseDate(String format, String date) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
        }
        return null;
    }

    /**
     * 获取 随机字符串
     *
     * @param length
     * @return
     */
    public static String getRandomStr(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int pos = random.nextInt(chars.length);
            sb.append(chars[pos]);
        }
        return sb.toString();
    }

    /**
     * 获取随机数字
     *
     * @param length: length<10
     * @return
     */
    public static int getRandomNum(int length) {
        if (length >= 10) {
            length = 9;
        }
        StringBuffer bound = new StringBuffer("8");
        StringBuffer start = new StringBuffer("1");
        for (int i = 1; i < length; i++) {
            bound.append("9");
            start.append("0");
        }
        int nextInt = new Random().nextInt(BaseTypeUtil.safeInt(bound));
        return nextInt + BaseTypeUtil.safeInt(start);
    }

    /**
     * 格式化 数字 小数
     *
     * @param money
     * @param digit：小数位数 >=0
     * @return
     */
    public static String formatNumber(Object money, int digit) {
        // 取值
        if (money instanceof BigDecimal) {
            money = ((BigDecimal) money).doubleValue();
        }

        DecimalFormat df = new DecimalFormat("#.##");
        if (digit < 0) {
            return df.format(money);
        }

        StringBuffer sb = new StringBuffer("#");
        if (digit > 0) {
            sb.append(".");
        }
        for (int i = 0; i < digit; i++) {
            sb.append("#");
        }
        df = new DecimalFormat(sb.toString());
        return df.format(money);
    }

    /**
     * MD5加密
     *
     * @param str
     * @return
     */
    public static String md5(String str, String salt) {
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update((str + salt).getBytes());
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < md.length; i++) {
                String shaHex = Integer.toHexString(md[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Object deserialize(String str) {
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            bis = new ByteArrayInputStream(Base64.decode(str));
            ois = new ObjectInputStream(bis);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException("deserialize session error", e);
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static String serialize(Object obj) {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            return Base64.encodeToString(bos.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("serialize session error", e);
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        String str = "rO0ABXNyACljb20uY21zLmJzLmFwcC5zaGlyby5zZXNzaW9uLlNoaXJvU2Vzc2lvbj3lIXe9EtPAAgABWgAJaXNDaGFuZ2VkeHIAKm9yZy5hcGFjaGUuc2hpcm8uc2Vzc2lvbi5tZ3QuU2ltcGxlU2Vzc2lvbp0cobjVjGJuAwAAeHB3AgCbdAAkYWFmZGI1NDktNjdlOS00MDhmLWEzZTAtYjk3NDE4MjdjMTFic3IADmphdmEudXRpbC5EYXRlaGqBAUtZdBkDAAB4cHcIAAABWGbk66B4cQB+AAV3CAAAAAAAG3dAc3IAEWphdmEudXRpbC5IYXNoTWFwBQfawcMWYNEDAAJGAApsb2FkRmFjdG9ySQAJdGhyZXNob2xkeHA/QAAAAAAADHcIAAAAEAAAAAN0AAtjdXJyZW50VXNlcnNyABljb20uY21zLmJzLmFwcC5tb2RlbC5Vc2VywkK2jZOeDKICAAhJAAZnZW5kZXJKAAJpZEkABnN0YXR1c0wACWxvZ2ludGltZXQAEExqYXZhL3V0aWwvRGF0ZTtMAARuYW1ldAASTGphdmEvbGFuZy9TdHJpbmc7TAAIbmlja25hbWVxAH4AC0wACHBhc3N3b3JkcQB+AAtMAAVyb2xlc3QAEExqYXZhL3V0aWwvTGlzdDt4cgAkY29tLmNtcy5icy5hcHAubW9kZWwuYmFzZS5CYXNlRW50aXR5kdFwZe3J4twCAAhMABBfZWJlYW5faW50ZXJjZXB0dAAqTGNvbS9hdmFqZS9lYmVhbi9iZWFuL0VudGl0eUJlYW5JbnRlcmNlcHQ7TAAIY3JlYXRlYnlxAH4AC0wACmNyZWF0ZXRpbWVxAH4ACkwACG1vZGlmeWJ5cQB+AAtMAAptb2RpZnl0aW1lcQB+AApMAAlwYWdlSW5kZXh0ABNMamF2YS9sYW5nL0ludGVnZXI7TAAIcGFnZVNpemVxAH4AD0wAC3F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2V0ukSFlZa4tzQDAAB4cHcMAAAAED9AAAAAAAABcQB+ABl4eAB3AQFxAH4AL3h4eAA=";
        Session session = (Session) CommonUtil.deserialize(str);
        System.out.println(session);
        User user = (User) session.getAttribute(Constants.CURRENT_USER);
        System.out.println(user);
    }

}
